package com.ingenio.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ingenio.business.Categoria;
import com.ingenio.dao.CategoriaAdapter;

/**
 * Servlet implementation class CategoriaServlet
 */
@WebServlet("/ServletCategoria")
public class ABMCategoriaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ABMCategoriaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String descripcion = "";
		Integer idCategoria = null;
		CategoriaAdapter ca = new CategoriaAdapter();
		Categoria c = null;
		if("delete".equals(request.getParameter("type"))){
			try {
				Integer id = Integer.parseInt(request.getParameter("id"));
		    	c = ca.devolverCategoria(id);
		    	ca.eliminarCategoria(c);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("edit".equals(request.getParameter("type"))){
			if(request.getParameter("descripcion_categoria") != null && request.getParameter("id_categoria_hidden") != null){
				descripcion = request.getParameter("descripcion_categoria");
				idCategoria = Integer.parseInt(request.getParameter("id_categoria_hidden"));
				try {
					c = ca.devolverCategoria(idCategoria);
					ca.modificarDescripcion(c, descripcion);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if("add".equals(request.getParameter("type"))){
			if(request.getParameter("descripcion_categoria") != null){
				descripcion = request.getParameter("descripcion_categoria");
				try {
					c = new Categoria(descripcion, true);
					ca.agregarCategoria(c);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		response.sendRedirect("categorias/listado_categorias.jsp");
	}

}
